﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Configuration;
using System.Data;
using System.IO;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["Metadataid"] == null)
        {
            Session["ReturnPage"] = "upload.aspx";
            Response.Redirect("metaData.aspx");
        }

        //Initial status text
        if (!IsPostBack)
        {
            status.InnerHtml = "<br /><p style='color: red;'>Awaiting file upload </p>";
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //Temp Upload Function//
        Session["Proc"] = "Upload";
        Session["Type"] = "File";
        HttpContext.Current.Session["SiteCode"] = null;
        //Response.Redirect("SubmittedResponse.aspx");
        ////



        if (FileUploadWDPA.FileName == "")
        {
            status.InnerHtml = "<br /><p style='color: red; text-align:left;'>Please ensure a file name has been provided.</p>";
        }
        else
        {




            StringBuilder myFileString = new StringBuilder();

            String dbConn = ConfigurationManager.ConnectionStrings["WDPAConnectionString1"].ConnectionString;
            System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection(dbConn);

            try
            {
                sqlConn.Open();
                StringBuilder myFileExQry = new StringBuilder();
                myFileExQry.Append("select * from InvalidFileEXTs");

                System.Data.SqlClient.SqlCommand myFileExRes = new System.Data.SqlClient.SqlCommand(myFileExQry.ToString(), sqlConn);

                System.Data.SqlClient.SqlDataReader readMyFileExRes;


                readMyFileExRes = myFileExRes.ExecuteReader(CommandBehavior.CloseConnection);

                Int32 startAt = FileUploadWDPA.FileName.ToString().LastIndexOf(".");

                String CheckMe = FileUploadWDPA.FileName.ToString().Substring(startAt + 1);
                while (readMyFileExRes.Read())
                {

                    if (readMyFileExRes[1].ToString() == CheckMe)
                    {
                        status.InnerHtml = "<br /><p style='color: red;'>Invalid file type. We cannot accept <b>'" + CheckMe + "'</b> files</p>";
                        return;
                    }

                }


            }
            catch (Exception ex)
            {
                status.InnerHtml = "<br /><p style='color: red;'>Invalid file type. [EC1FT]</p>";
                return;
            }
            finally
            {
                sqlConn.Close();



            }


            myFileString.Append("\\\\wcmc-gis-01\\WDPA_workflow\\UploadedData\\");
            myFileString.Append(Context.User.Identity.Name.ToString());
            myFileString.Append(@"\");
            myFileString.Append(DateTime.Now.Year.ToString());
            myFileString.Append(DateTime.Now.Month.ToString());
            myFileString.Append(DateTime.Now.Day.ToString());
            myFileString.Append(DateTime.Now.Hour.ToString());
            myFileString.Append(DateTime.Now.Minute.ToString());
            myFileString.Append(DateTime.Now.Second.ToString());
            myFileString.Append(DateTime.Now.Millisecond.ToString());


            if (!Directory.Exists(myFileString.ToString()))
            {
                Directory.CreateDirectory(myFileString.ToString());
            }



            try
            {
                sqlConn.Open();
                StringBuilder myInsert = new StringBuilder();
                myInsert.Append("insert into dataset (Dataset_Ref, MetadataID, Data_Provider_ID, Path, Received_Date) values(");
                myInsert.Append("'" + DataSetRef.Value.ToString() + "',");
                myInsert.Append(Session["Metadataid"].ToString() + ",");
                myInsert.Append("'" + Context.User.Identity.Name.ToString() + "',");
                myInsert.Append("'" + myFileString.ToString() + "',");
                myInsert.Append("getdate())");
                System.Data.SqlClient.SqlCommand InsertCommand = new System.Data.SqlClient.SqlCommand(
                    myInsert.ToString(), sqlConn);
                InsertCommand.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                status.InnerHtml = "<br /><p style='color: red;'>Error writing file to database. [" + ex.Message + "]</p>";
                return;
            }
            finally
            {
                sqlConn.Close();
            }




            myFileString.Append(@"\");
            myFileString.Append(FileUploadWDPA.FileName.ToString());

            FileUploadWDPA.PostedFile.SaveAs(myFileString.ToString());
            status.InnerHtml = "<br/>File " + FileUploadWDPA.FileName.ToString() + " has been posted";
            Session["Proc"] = "Upload";
            Session["Type"] = "File";
            HttpContext.Current.Session["SiteCode"] = null;
            //Session["Metadataid"] = null;
            Response.Redirect("SubmittedResponse.aspx");
        }

    }

}

